#include <iostream>
#include <ctime>
#include "writevideo.h"
#include "opencv2/myopencv.hpp"

using namespace std;

cv::VideoWriter vw;
int cols, rows;
FILE* recFile;
int fct = 0;
int createTime;
char outfile[100];

WRITEVIDEO_API int fnWriteVideo(uchar* data, int bytePerPixel)
{
	if (!vw.isOpened()) return 1;
	CvMat *mat = cvCreateMatHeader(rows, cols, CV_MAKETYPE(CV_8U,bytePerPixel));
	mat->data.ptr = data;
	cvShowImage("write video", mat);
	vw.write(mat);
	return 0;
}

WRITEVIDEO_API void fnKeepData(short* data, int bytePerPixel)
{
	++fct;
	CvMat *mat = cvCreateMatHeader(rows, cols, CV_MAKETYPE(CV_16S,bytePerPixel));
	mat->data.s = data;
// 	CvMat *newMat = cvCreateMat(rows, cols, CV_MAKETYPE(CV_64F, bytePerPixel));
// 	double minV, maxV;
// 	cvMinMaxLoc(mat, &minV, &maxV);
// 	cvConvertScale(mat, newMat, 1, -5000);
// 	cvConvertScale(newMat, newMat, 1/1000.0, 0);
	cvShowImage("keep data", mat);
// 	cvReleaseMat(&newMat);
	fwrite(data, sizeof(short), rows*cols*bytePerPixel, recFile);
}

WRITEVIDEO_API int fnInitVideo(char* name, int fourcc, double fps, int w, int h) {
	if (vw.isOpened()) return 0;
	createTime = time(0);

// 	memset(outfile,0,100);
// 	sprintf(outfile, "color_%d.avi", createTime);
// 	vw.open(outfile, fourcc, fps, cv::Size(w, h));

	cols = w;
	rows = h;
	cvNamedWindow("write video");

	memset(outfile, 0, 100);
	sprintf_s(outfile, "depthData_%d.txt", createTime);
	fopen_s(&recFile, outfile, "wb");
	fprintf_s(recFile, "%d %d\n", cols, rows);
	
	return vw.isOpened()?0:1;
}

WRITEVIDEO_API void fnCloseVideo(void) {
	if (recFile != NULL) {
		fclose(recFile);
		cout << "depth record file close success." << endl;
		recFile = NULL;
	}
	if (vw.isOpened()) {
		vw.~VideoWriter();
		cout << "color video save success." << endl;
	}

}

WRITEVIDEO_API void fnTest( char* name ) {
	//cout << name << endl;
	cout << strlen(name) << endl;
	cvNamedWindow("hello~");
	CvMat *mat = cvCreateMatHeader(480, 640, CV_8UC4);
	mat->data.ptr = (uchar*) name;
// 	CvMat *mat = cvCreateMat(480, 640, CV_8UC3);
// 	uchar* ptr = mat->data.ptr;
// 	printf("%d %d %d %d\n", *name, *(name+1), *(name+2), *(name+3));
// 	for (int i=0; i<480; ++i) {
// 		for (int j=0; j<640; ++j, ptr+=3, name+=4) {
// 			*ptr = *(name+3);
// 			*(ptr+1) = *(name+2);
// 			*(ptr+2) = *(name+1);
// 		}
// 	}
	cvShowImage("hello~", mat);
// 	CvMat *img = cvLoadImageM("gray.jpg");
// 	cvNamedWindow("direct");
// 	cvShowImage("direct", img);
}

int main(void) {
	cout << vw.isOpened() << endl;
	fnInitVideo("test.avi", -1, 30, 640, 480);
	cout << vw.isOpened() << endl;
	vw.~VideoWriter();
	return 0;
}

